package com.zkingsoft.actions.client;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.alipay.config.AlipayConfig;
import com.zkingsoft.alipay.util.AlipayNotify;
import com.zkingsoft.alipay.util.AlipaySubmit;
import com.zkingsoft.config.Dictionary;
import com.zkingsoft.model.Agent;
import com.zkingsoft.model.Clubdata;
import com.zkingsoft.model.ExtensionDetail;
import com.zkingsoft.model.PaginationVO;
import com.zkingsoft.model.RechargeDetail;
import com.zkingsoft.model.TradeRecord;
import com.zkingsoft.model.Userdata;
import com.zkingsoft.model.Users;
import com.zkingsoft.model.WeixinAccessToken;
import com.zkingsoft.model.WeixinUserInfo;
import com.zkingsoft.plugin.util.FileDownload;
import com.zkingsoft.plugin.util.HttpUtils;
import com.zkingsoft.plugin.util.StringUtils;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.pojo.Result;
import com.zkingsoft.services.AgentService;
import com.zkingsoft.services.ClubdataService;
import com.zkingsoft.services.ExtensionDetailService;
import com.zkingsoft.services.RechargeDetailService;
import com.zkingsoft.services.TradeRecordService;
import com.zkingsoft.services.UserdataService;
import com.zkingsoft.services.UsersService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/client")
public class ClientController extends BaseController {
	private static final String APP_ID = "wx5f684362422f302e";
	private static final String SECRET = "7ec40acc47d4ba02540b758321c58b7a";
	private static final Logger log = Logger.getLogger(ClientController.class);
	
	private TradeRecord trade;
	private String clubNames;

	@Resource
	private RechargeDetailService rechargeService;
	@Resource
	private ExtensionDetailService extensionService;
	@Resource
	private UsersService userService;
	@Resource
	private TradeRecordService tradeService;
	@Resource
	private AgentService agentService;
	@Resource
	private UserdataService userDataService;
	@Resource
	private ClubdataService clubdataService;
/**
 * 推广详情页面
 * @param userId
 * @return
 */
	@RequestMapping(value = "/toExtension")
	public @ResponseBody Result toExtension(Integer gameId,String token) {
		Result result = new Result();
		log.info("分享页面1..."+gameId);
		//是否已经成为代理
		Users user = userService.findByGameId(gameId);
		log.info("分享页面2..."+user);
		if(user==null){//新代理
			Userdata userdata = userDataService.findById(gameId);
			log.info("分享页面3..."+userdata);
			if(userdata==null){
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("不存在该游戏账号！");
				return result;
			}
			if(!token.equals(userdata.getToken())){
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("token信息不正确");
				return result;
			}
			//判断是否还有推广名额
			Agent agent = agentService.findById(1L);
			if(agent.getStatus()==2){//关闭推广
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("推广活动已经结束");
				return result;//推广活动结束
			}else if(agent.getStatus()==1){//开启推广，限定人数
				//查询当前代理人数
				Users users = new Users();
				users.setTgRight(1);//有推广权限
				int total = userService.findTotal(users);//有推广权限的人数
				if(total>=agent.getNum()){//超出代理人数限制
					result.setCode(Result.STATUS_FALSE);
					result.setMsg("超出代理人数限制");
					return result;//推广活动结束
				}else{
					log.info("else...");
					//创建一个代理人
					Users newUser = new Users();
					newUser.setName(userdata.getName());
					newUser.setWeixinId(userdata.getWxid());
					newUser.setSex(userdata.getSex().toString());
					newUser.setRoleId(20L);
					newUser.setRegisterTime(new Date());
					newUser.setValid(1);
					newUser.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
					newUser.setCompanyId(17L);
					newUser.setAccount(Dictionary.ACCOUNT_STATUS_ACTIVATE);
					newUser.setExtensionMoney(0.0);
					newUser.setTgRight(1);
					newUser.setGameId(gameId);
					userService.add(newUser);
					user = userService.findByGameId(gameId);
				}
			}
		}
		//查询推广记录
		Map<String, Object> map = new HashMap<String,Object>();
		/*ExtensionDetail detail = new ExtensionDetail();
		List<ExtensionDetail> list = null;
			detail.setUserParentId(user.getId());
			detail.setStatus(2);
			list = extensionService.findByModel(detail);
			for (ExtensionDetail extensionDetail : list) {
				if(extensionDetail.getCreateTime()!=null){
					Date date = new Date(extensionDetail.getCreateTime());
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
					String str = sdf.format(date);
					extensionDetail.setStrDate(str);
				}
			}
			System.out.println("大小:"+list.size());*/
			// getRequest().setAttribute("extensions", list);
			// getSession().setAttribute("user", user);
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5f684362422f302e&redirect_uri=http://www.jjstar.cc/client/getweixinInfo/"+user.getId()+"&response_type=code&scope=snsapi_userinfo&state=3d6be0a4035d839573b04816624a416e#wechat_redirect";
			map.put("url", url);
			map.put("userId", user.getId());
			map.put("coin", user.getExtensionMoney());
			result.setCode(Result.STATUS_TRUE);
			result.setResult(map);
			result.setMsg("推广数据获取成功！");
			return result;
	}
	
	/**
	 * 推广详情页面
	 * @param userId
	 * @return
	 */
		@RequestMapping(value = "/extenDetail")
		public @ResponseBody Result extenDetail(Long userId,PaginationVO page) {
			Result result = new Result();
			Map<String, Object> map = new HashMap<String,Object>();
			ExtensionDetail detail = new ExtensionDetail();
			List<ExtensionDetail> list = null;
			
			if(userId!=null){
				detail.setUserParentId(userId);
				detail.setStatus(2);
				int total = extensionService.findTotal(detail);
				System.out.println("大小:"+total);
					page.setOffset(page.getOffset()*total);
					list = extensionService.findInPage(detail,page);
				for (ExtensionDetail extensionDetail : list) {
					if(extensionDetail.getCreateTime()!=null){
						Date date = new Date(extensionDetail.getCreateTime());
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
						String str = sdf.format(date);
						extensionDetail.setStrDate(str);
					}
				}
				System.out.println("大小:"+list.size());
				map.put("extensions", list);
				result.setCode(Result.STATUS_TRUE);
				result.setResult(map);
				result.setMsg("推广数据获取成功！");
			}else{
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("推广数据获取失败！");
			}
			return result;
		}
	
	/**
	 * 推广详情页面（废弃的方法）
	 * @param userId
	 * @return
	 */
		@RequestMapping(value = "/toExtension1")
		public String toExtension1(Integer gameId,String token,String weixinId) {
			log.info("分享页面..."+gameId);
			//是否已经成为代理
			Users user = userService.findByGameId(gameId,weixinId);
			if(user==null){//新代理
				Userdata userdata = userDataService.findByWeixinId(gameId,weixinId);
				if(userdata==null){
					return "common/redirect/404";
				}
				if(!token.equals(userdata.getToken())){
					return "common/redirect/404";
				}
				//判断是否还有推广名额
				Agent agent = agentService.findById(1L);
				if(agent.getStatus()==2){//关闭推广
					return "client/extension-over";//推广活动结束
				}else if(agent.getStatus()==1){//开启推广，限定人数
					//查询当前代理人数
					Users users = new Users();
					users.setTgRight(1);//有推广权限
					int total = userService.findTotal(users);//有推广权限的人数
					if(total>=agent.getNum()){//超出代理人数限制
						return "client/extension-over";//推广活动结束
					}else{
						//创建一个代理人
						Users newUser = new Users();
						newUser.setName(userdata.getName());
						newUser.setWeixinId(userdata.getWxid());
						newUser.setSex(userdata.getSex().toString());
						newUser.setRoleId(20L);
						newUser.setRegisterTime(new Date());
						newUser.setValid(1);
						newUser.setUserType(Dictionary.USER_TYPE_EMPLOYEE);
						newUser.setCompanyId(17L);
						newUser.setAccount(Dictionary.ACCOUNT_STATUS_ACTIVATE);
						newUser.setExtensionMoney(0.0);
						newUser.setTgRight(1);
						newUser.setGameId(gameId);
						userService.add(newUser);
						user = userService.findByGameId(gameId,weixinId);
					}
				}
			}
			//查询推广记录
			ExtensionDetail detail = new ExtensionDetail();
			List<ExtensionDetail> list = null;
				detail.setUserParentId(user.getId());
				detail.setStatus(2);
				list = extensionService.findByModel(detail);
				for (ExtensionDetail extensionDetail : list) {
					if(extensionDetail.getCreateTime()!=null){
						Date date = new Date(extensionDetail.getCreateTime());
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
						String str = sdf.format(date);
						extensionDetail.setStrDate(str);
					}
				}
				System.out.println("大小:"+list.size());
				getRequest().setAttribute("extensions", list);
				getSession().setAttribute("user", user);
			return "client/extension-app";
		}

	
	@RequestMapping(value = "/getweixinInfo/{userId}")
	public String getWinXinUserInfo(@PathVariable("userId")Long userId,String code,String state){
		Users user = userService.findById(userId);
		if(user!=null){
			if(StringUtils.isNotBlank(code)){
				//微信扫描登录获取用户信息
				getWeixinUserInfo(userId,code);
			}
		}else{
			return "common/redirect/404";//跳到404.jsp
		}
		return "download";
	}
	
	/**
	 * app下载页面
	 * @param userId
	 * @param code
	 * @param state
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toDownload")
	public String toDownload(Long userId,String code,String state) throws Exception {
		log.info("下载页面..."+userId);
		Users user = userService.findById(userId);
		if(user!=null){
			if(StringUtils.isNotBlank(code)){
				//微信扫描登录获取用户信息
				boolean result = getWeixinUserInfo(userId,code);
				if(result){
					getRequest().setAttribute("result", "ok");
				}
			}
			getRequest().setAttribute("user", user);
		}else{
			return "common/redirect/404";//跳到404.jsp
		}
		return "client/download-app";
	}
	
	
	/**
	 * 获取微信授权用户信息
	 * @param userId
	 * @param code
	 * @return
	 */
	private boolean getWeixinUserInfo(Long userId, String code) {
			//获取access_token
			String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
			String param = "appid="+APP_ID+"&secret="+SECRET+"&code="+code+"&grant_type=authorization_code";
			String data = HttpUtils.sendGet(url, param);
			log.info(data);
			Gson gson = new Gson();
			WeixinAccessToken access = gson.fromJson(data, WeixinAccessToken.class);
			if(StringUtils.isNotBlank(access.getOpenid())){
				//获取用户信息
				String url1 = "https://api.weixin.qq.com/sns/userinfo";
				String param1 = "access_token="+access.getAccess_token()+"&openid="+access.getOpenid();
				String data1 = HttpUtils.sendGet(url1, param1);
				JSONObject jsonObject = JSONObject.fromObject(data1.trim());
				WeixinUserInfo userInfo = (WeixinUserInfo) JSONObject.toBean(jsonObject,WeixinUserInfo.class);
				//判断微信号是否已登录游戏
				if(/*//mlg修改 isLoginGame(userInfo)&&*/isSameUser(userInfo, userId) || isBindWeixin(userInfo)){
//					if(isBindWeixin(userInfo)){//判断微信号是否已绑定
					/*//mlg修改
					ExtensionDetail detail = extensionService.findByWeiXinId(userInfo.getUnionid());
					detail.setStatus(2);
					extensionService.modify(detail);
					Users user = userService.findById(userId);
					RechargeDetail recharge = new RechargeDetail();
					recharge.setType(3);
					RechargeDetail rechargeDetail = rechargeService.findByType(recharge);
					if(user.getExtensionMoney()!=null){
						user.setExtensionMoney((rechargeDetail.getBackMoney()==null?0:rechargeDetail.getBackMoney())+user.getExtensionMoney());
					}else{
						user.setExtensionMoney(rechargeDetail.getBackMoney()==null?0:rechargeDetail.getBackMoney());
					}
					userService.modify(user);*/
					return true;
//					}
//					else{
//						getSession().setAttribute("isbind", "yes");//已绑定推广人
//					}
				}else{
					//获取返利金额
					RechargeDetail recharge = new RechargeDetail();
					recharge.setType(3);
					RechargeDetail rechargeDetail = rechargeService.findByType(recharge);
					ExtensionDetail detail = new ExtensionDetail();
					detail.setStatus(1);//未登录
					detail.setUserParentId(userId);
					detail.setDescriptions("下载奖励");
					detail.setMoney(rechargeDetail.getGiveNum()==null?0:Double.valueOf(rechargeDetail.getGiveNum()));
					detail.setWeixinBindId(userInfo.getUnionid());
					detail.setCreateTime(new Date().getTime());
					int num = extensionService.add(detail);
					return true;
					/*if(num>0){
						Users user = userService.findById(userId);
						if(user.getExtensionMoney()!=null){
							user.setExtensionMoney((rechargeDetail.getBackMoney()==null?0:rechargeDetail.getBackMoney())+user.getExtensionMoney());
						}else{
							user.setExtensionMoney(rechargeDetail.getBackMoney()==null?0:rechargeDetail.getBackMoney());
						}
						userService.modify(user);
						return true;
					}*/
				}
//				else{
//					getSession().setAttribute("islogin", "yes");//已登录游戏
//				}
			}
		return false;
	}

	/**
	 * 判断是否绑定微信
	 * @param userInfo
	 * @return
	 */
private boolean isBindWeixin(WeixinUserInfo userInfo) {
	ExtensionDetail extensionDetail = extensionService.findByWeiXinId(userInfo.getUnionid());
	if(extensionDetail!=null){//已经绑定,跳转到下载页面
		return true;
	}
	return false;
}
/**
 * 判断是否已登录游戏
 * @param userInfo
 * @return
 */
private boolean isLoginGame(WeixinUserInfo userInfo) {
	Userdata userdata = userDataService.findByWeixinId(userInfo.getUnionid());
	if(userdata!=null){//已登录游戏
		return true;
	}
	return false;
}
/**
 * 判断是否是推广人自己
 * @param userInfo
 * @author mlg
 * @return
 */
private boolean isSameUser(WeixinUserInfo userInfo, Long userId) {
	Users user = userService.findById(userId);
	if(user != null) {
		if(userInfo.getUnionid().equals(user.getWeixinId())) {
			return true;
		}
	}
	return false;
}
	/**
	 * 进入充值页面
	 * @param gameId
	 * @param token
	 * @return
	 */
	@RequestMapping(value = "/toRecharge")
	public String toRecharge(Integer gameId,String token,String weixinId) {
		log.info("查询充值细则..."+gameId);
		List<RechargeDetail> clubs = new ArrayList<RechargeDetail>();
		List<RechargeDetail> diamonds = new ArrayList<RechargeDetail>();
		List<RechargeDetail> list = rechargeService.findByModel(null);
		for (RechargeDetail rechargeDetail : list) {
			if(rechargeDetail.getType()==1){
				clubs.add(rechargeDetail);
			}else if(rechargeDetail.getType()==2){
				diamonds.add(rechargeDetail);
			}
		}
		Userdata userdata = userDataService.findByWeixinId(gameId, weixinId);
		if(userdata==null){
			return "common/redirect/404";
		}
		if(!token.equals(userdata.getToken())){
			return "common/redirect/404";
		}
		if(userdata.getCreateclubid() != -1) {
			Clubdata clubdata = clubdataService.findById(userdata.getCreateclubid());
			if(clubdata != null) {
				getRequest().setAttribute("clubname", clubdata.getClubname());
			}
		}
		getRequest().setAttribute("clubs", clubs);
		getRequest().setAttribute("diamonds", diamonds);
		getSession().setAttribute("gameUser", userdata);
		return "client/recharge-app";
	}
	
	/**
	 * 钻石转账
	 * @param receiveId
	 * @param outNum
	 * @return
	 */
	@RequestMapping(value = "/outDiamond")
	@Transactional(value="transactionManager",rollbackFor=java.lang.Exception.class)
	public @ResponseBody Result outDiamond(Integer receiveId,int outNum ){
		log.info("钻石转账..."+receiveId);
		Result result = new Result();
		Userdata userdata = (Userdata)getSession().getAttribute("gameUser");
		Userdata userdata2 = userDataService.findById(receiveId);
		if(userdata!=null&&userdata2!=null){
			if(userdata.getDiamondnum()>0&&userdata.getDiamondnum()>=outNum){
				int num = userDataService.updateDiamond(userdata.getUserid(), userdata.getDiamondnum()-outNum);
				int num2 = userDataService.updateDiamond(userdata2.getUserid(), userdata2.getDiamondnum()+outNum);
				if(num>0&&num2>0){//转账成功
					result.setCode(Result.STATUS_TRUE);
					result.setMsg("转账成功");
				}else{
					result.setCode(Result.STATUS_ERR);
					result.setMsg("转账失败");
				}
			}else{
				result.setCode(Result.STATUS_FALSE);
				result.setMsg("钻石余额不足");
			}
		}
		return result;
	}
	
	
	
	
	@RequestMapping(value = "/toPayDetail")
	public String toPayDetail() {
		log.info("支付详情页面...");
		return "client/pay-detail";
	}
	
	@RequestMapping(value = "/download-app")
	public String downloadApp(Integer type) {
		log.info("下载app页面..."+type);
		if(type!=null&&type==1){
			getRequest().setAttribute("tip", "您的帐号已绑定好友，下载并登录游戏即可获得丰厚奖励！");
		}
		return "download";
	}

	
	/**
	 * 提现
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/getCash")
	public @ResponseBody AjaxResult getCash(Integer gameId,String account) {
		log.info("游戏编号："+gameId+"  支付宝："+account);
		boolean result = false;
		try {
			result = tradeService.postCash(gameId,account);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(result){
			return new AjaxResult(AjaxResult.STATUS_OK, null, "处理成功");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "处理失败");
	}
	
	/**
	 * 判断用户是否存在
	 * @param gameId
	 * @return
	 */
	@RequestMapping(value = "/getGameUser")
	public @ResponseBody Result getGameUser(Integer gameId) {
		Result result = new Result();
		log.info("判断游戏用户ID是否存在..."+gameId);
		Userdata user = userDataService.findById(gameId);
		if(user==null){
			result.setCode(Result.STATUS_FALSE);
		}else{
			result.setCode(Result.STATUS_TRUE);
			//判断是否已加满10个俱乐部  by mlg
			if(user.getJoinclubnum().equals(10) || user.getJoinclubnum() >= 10) {
				result.setMsg("fullClubs");
			}
		}
		return result;
	}
	
	
	/**
	 * 支付
	 */
	@RequestMapping(value = "/toPay")
	public void toPay(Long rechargeId,Integer gameId,String clubName,HttpServletResponse response) throws IOException{
		//clubName = java.net.URLDecoder.decode(clubName, "ISO-8859-1");
		clubName = new String(clubName.getBytes("ISO-8859-1"), "UTF-8");
		log.info("去支付。。。gameId==>"+gameId+"rechargeId==>"+rechargeId+"clubName==>"+clubName);
		PrintWriter out = response.getWriter();
		response.setCharacterEncoding("utf-8");        
	    response.setContentType("text/html; charset=utf-8");
		String sHtmlText = "";
		StringBuilder html = new StringBuilder();
		Userdata user = userDataService.findById(gameId);
		if(user!=null){
			RechargeDetail rechargeDetail = rechargeService.findById(rechargeId);
			//创建一条交易记录
			clubNames = clubName;
			String code = getUUID();
			trade = new TradeRecord();
			trade.setCode(code);
			trade.setUserId(gameId);
			trade.setRechargeId(rechargeId);
			trade.setRechargeTime(new Date().getTime());
			trade.setStatus(3);
			//trade.setMoney(0.01);
///			getSession().setAttribute("trade", trade);
//			getSession().setAttribute("clubName", clubName);
			trade.setMoney(rechargeDetail.getMoney());
//			int num = tradeService.add(trade);
//			if(num>0){
			//把请求参数打包成数组
					Map<String, String> sParaTemp = new HashMap<String, String>();
					sParaTemp.put("service", AlipayConfig.service);
			        sParaTemp.put("partner", AlipayConfig.partner);
			        sParaTemp.put("seller_id", AlipayConfig.seller_id);
			        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
					sParaTemp.put("payment_type", AlipayConfig.payment_type);
					sParaTemp.put("notify_url", AlipayConfig.notify_url);
					sParaTemp.put("return_url", AlipayConfig.return_url);
					sParaTemp.put("out_trade_no", code);
					sParaTemp.put("subject", rechargeDetail.getDescription());
					//sParaTemp.put("total_fee", rechargeDetail.getMoney().toString());
					sParaTemp.put("total_fee", "0.01");
					sParaTemp.put("show_url", "pay.jjstar.cc/client/toPayDetail");
					sParaTemp.put("body", "");
//					sParaTemp.put("app_pay", "N");//禁止app支付
					
					//其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
			        //如sParaTemp.put("参数名","参数值");
					//建立请求
					sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
//			}else{
//				sHtmlText = "<div>网络繁忙，请稍后再试！</div>";
//			}
			html.append("<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"
					+"<title>支付宝手机网站支付</title></head><body>"+sHtmlText+"</body></html>");
			out.println(html);
		}else{
			out.println("<script>alert('用户ID不存在')</script>");
		}
		
	}

	/**
	 * 同步返回支付结果
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/toPayTipGet")
	public String toPayTip(String out_trade_no,String trade_no,String trade_status,HttpServletResponse response) throws IOException{
		//获取支付宝GET过来反馈信息
		PrintWriter out = response.getWriter();
		response.setCharacterEncoding("utf-8");        
	    response.setContentType("text/html; charset=utf-8");
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = getRequest().getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		
		//计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params);
		if(verify_result){//验证成功
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				//添加交易记录.设置交易状态为成功
//				TradeRecord tradeRecord = tradeService.findByCode(out_trade_no);
//				TradeRecord tradeRecord = (TradeRecord) getSession().getAttribute("trade");
//				String clubName = (String) getSession().getAttribute("clubName");
				tradeService.dealRechargeBusindess(trade,1, trade_no,clubNames);
			}
			getSession().removeAttribute("trade");
			getSession().removeAttribute("clubName");
			//out.println("验证成功<br />");
			return "client/pay-tip-success";
		}else{
//			out.println("验证失败");
			return "client/pay-tip-fail";
		}
	}

	
	/**
	 * 异步通知信息
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/toPayTipPost")
	public void toPayTipPost(String out_trade_no,String trade_no,String trade_status,
			String total_fee,String seller_id,HttpServletResponse response) throws IOException{
		//获取支付宝POST过来反馈信息
		PrintWriter out = response.getWriter();
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = getRequest().getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		if(AlipayNotify.verify(params)){//验证成功
			if(trade_status.equals("TRADE_FINISHED")||trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
					//如果有做过处理，不执行商户的业务程序
				//设置交易状态为完成
//				TradeRecord tradeRecord = tradeService.findByCode(out_trade_no);
//				TradeRecord tradeRecord = (TradeRecord) getSession().getAttribute("trade");
//				String clubName = (String) getSession().getAttribute("clubName");
				//if(trade.getMoney()==Double.parseDouble(total_fee)&&seller_id.equals(AlipayConfig.seller_id)){
					tradeService.dealRechargeBusindess(trade,1, trade_no,clubNames);
				//}
			} 
			getSession().removeAttribute("trade");
			getSession().removeAttribute("clubName");
			out.print("success");	//请不要修改或删除
		}else{//验证失败
			out.print("fail");
		}
	}
	
	
	/**下载apk*/
	@RequestMapping(value = "/downloadApk")
	public void downloadApk(HttpServletResponse response) throws Exception {
		String path = getSession().getServletContext().getRealPath("WEB-INF/views/apk/jjstar-pdk.apk");
		File file = new File(path);
		FileDownload.downloadFile(getRequest(), response, file);
	}
	
	/**生成32位编码  
     * @return string  
     */    
   public static String getUUID(){    
       return UUID.randomUUID().toString().trim().replaceAll("-", "");    
   } 
   
   /**
	 * 判断用户是否存在
	 * @param gameId
	 * @return
	 */
	@RequestMapping(value = "/shareUrl")
	public @ResponseBody Result shareUrl(Integer gameId) {
		Result result = new Result();
		Users user = userService.findByGameId(gameId);
		if(user==null){
			result.setMsg("异常！");
			result.setCode(Result.STATUS_FALSE);
		}
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5f684362422f302e&redirect_uri=http://www.jjstar.cc/client/getweixinInfo/"+user.getId()+"&response_type=code&scope=snsapi_userinfo&state=3d6be0a4035d839573b04816624a416e#wechat_redirect";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("url", url);
		result.setResult(map);
		result.setMsg("成功获取地址！");
		result.setCode(Result.STATUS_TRUE);
		return result;
	}
   
   
}